package it.mp.acquaalta;

import it.mp.acquaalta.utility.DecodificaPagina;
import java.io.IOException;
import java.io.Serializable;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;

public class LoadAsyncTask extends AsyncTask<Void, Void, Boolean> implements Serializable{
	private static final long serialVersionUID = 4220327066182351841L;
	private Context ctx;
	private Handler messageHandler;	
	public LoadAsyncTask(Context ctx,Handler messageHandler){
		this.ctx=ctx;
		this.messageHandler=messageHandler;		
	}
	
	public static final int DOWNLOAD_ID=200;
	public static final int ERRORIDENTIFIER=-1;
	public static final int PROGRESS=100;
    protected Boolean doInBackground(Void... params) {         
        boolean success = false;  
             try {
				success = downloadAttempt();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				e.printStackTrace();
			} 
                     
        return success; 
       }
    
        protected void onPostExecute(Boolean success) { 
        	//remove progress dialog if you set one up... 
        	if(success){ 
        		Message m = new Message(); 
        		m.what = DOWNLOAD_ID; 
        		messageHandler.sendMessage(m); 
        	}else{ 
        		Message m = new Message(); 
        		m.what = ERRORIDENTIFIER; 
        		messageHandler.sendMessage(m); 
        	} 
       }
       
       private boolean downloadAttempt() throws IOException, SAXException, ParserConfigurationException{
    	   boolean fatto=true;
    	    try {
				DecodificaPagina previsione=new DecodificaPagina(ctx);
				if ((previsione.getBean() == null) || (previsione.getBean().alBean == null) || ((previsione.getBean().alBean.size() == 0))
						|| (previsione.getBean().alBean.get(0).data == null)) {				
					fatto=false;
				}else{
					previsione.getBean().toSharedPreferences(ctx);
				}				
			} catch (Exception e) {
				fatto=false;
				e.printStackTrace();
			}
			Intent i=new Intent();
			i.setAction("AGGIORNA_WIDGET_AA");
    	    ctx.sendBroadcast(i);
   			return fatto;
       } 		
       
       public void setMessageHandler(Handler msg){
    	   messageHandler=msg;
       }
}
